package com.yangtzeu.jwc.dao.impl;

import java.util.Map;

import org.apache.http.Header;

import android.content.Context;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.PersistentCookieStore;
import com.loopj.android.http.RequestParams;
import com.zjsx.lib.utils.L;

public class HttpDaoImpl {
    private Context ctx;
    private AsyncHttpClient client;
    PersistentCookieStore cookieStore;

    public HttpDaoImpl(Context ctx) {
        this.ctx = ctx;
        this.cookieStore = new PersistentCookieStore(ctx);
        this.client = new AsyncHttpClient();
        this.client.setTimeout(10 * 1000);
        this.client.setCookieStore(cookieStore);
    }

    public PersistentCookieStore getCookieStore() {
        return cookieStore;
    }

    public void setCookieStore(PersistentCookieStore cookieStore) {
        this.cookieStore = cookieStore;
    }

    /**
     * 无参数的Http参数
     *
     * @param url
     * @param responseHandler
     */
    public void doHttpRequest(Context context, String url, final AsyncHttpResponseHandler responseHandler) {
        doHttpRequest(context, url, null, responseHandler);
    }

    /**
     * 执行Http请求 ， 默认都是使用的post的方式
     *
     * @param context
     * @param url
     * @param paramsMap
     * @param responseHandler
     */
    public void doHttpRequest(Context context, final String url, final Map<String, String> paramsMap, final AsyncHttpResponseHandler responseHandler) {
        L.d("访问地址：" + url);
        RequestParams params = new RequestParams(paramsMap);
        client.post(url, params, new AsyncHttpResponseHandler() {

            @Override
            public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
                L.d("请求失败：" + arg3.getMessage() + paramsMap);
                responseHandler.onFailure(arg0, arg1, arg2, arg3);
            }

            @Override
            public void onProgress(int bytesWritten, int totalSize) {
                responseHandler.onProgress(bytesWritten, totalSize);
            }

            @Override
            public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
                L.d("请求成功：" + url);
                responseHandler.onSuccess(arg0, arg1, arg2);
            }

        });
    }
}
